const Stripe = require("stripe");
const stripe = Stripe(
  "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" //王
  // "sk_test_51ROwErEHIcYxLscx4pG8KWZ6w4suY6busha9vax4Mvy9QiroH7UKQHi76kTdgZIhtKp43oiz0OL7QN3tWb9O4EbZ009P4unREn" //myself
);

// 引入新的模型
const PaymentOrder = require("../models/PaymentOrder");
const ProductConfig = require("../models/ProductConfig");
const UserBenefit = require("../models/UserBenefit");
const TokenTransaction = require("../models/TokenTransaction");
const Visitor = require("../models/Visitor");
const { sequelize } = require("../config/database");

// 检查用户会员等级是否满足产品要求
async function checkUserMembershipLevel(stripe_price_id, user_uuid) {
  try {
    // 获取产品配置
    const productConfig = await ProductConfig.findOne({
      where: { stripe_price_id, is_active: true },
    });

    if (!productConfig) {
      return {
        success: false,
        message: "请先升级会员，才可享受该折扣哦！",
        required_tier: null,
        current_tier: null,
        membership_expired: false,
      };
    }

    // 如果产品不需要会员等级，直接通过
    if (!productConfig.membership_tier) {
      return { success: true };
    }

    // 获取用户信息
    const visitor = await Visitor.findOne({
      where: { uuid: user_uuid },
    });

    if (!visitor) {
      return {
        success: false,
        message: "请先升级会员，才可享受该折扣哦！",
        required_tier: productConfig.membership_tier,
        current_tier: null,
        membership_expired: false,
      };
    }

    // 获取用户权益信息
    const userBenefit = await UserBenefit.findOne({
      where: { user_uuid },
    });

    // 检查会员是否过期
    const now = new Date();
    const membershipExpired =
      !visitor.membership_expires_at || visitor.membership_expires_at < now;

    // 获取当前用户等级
    const currentTier = userBenefit?.membership_tier || null;

    // 如果会员已过期，当前等级视为null
    const effectiveTier = membershipExpired ? null : currentTier;

    // 检查等级是否满足要求
    if (!effectiveTier || effectiveTier < productConfig.membership_tier) {
      return {
        success: false,
        message: "请先升级会员，才可享受该折扣哦！",
        required_tier: productConfig.membership_tier,
        current_tier: effectiveTier,
        membership_expired: membershipExpired,
      };
    }

    return { success: true };
  } catch (error) {
    console.error("Error checking user membership level:", error);
    return {
      success: false,
      message: "请先升级会员，才可享受该折扣哦！",
      required_tier: null,
      current_tier: null,
      membership_expired: false,
    };
  }
}

// 通用的创建订单方法
async function createOrder(stripe_price_id, user_uuid, email, payment_method) {
  // 验证产品配置
  const productConfig = await ProductConfig.findOne({
    where: { stripe_price_id, is_active: true },
  });

  if (!productConfig) {
    throw new Error("Invalid or inactive product");
  }

  // 获取 Stripe 价格信息
  const price = await stripe.prices.retrieve(stripe_price_id);

  // 根据产品类型确定订单类型
  let orderType;
  if (productConfig.product_type === "subscription") {
    orderType = "subscription"; // 订阅类型
  } else {
    orderType = "disposable"; // 一次性支付
  }

  // 创建订单记录
  const order = await PaymentOrder.create({
    user_uuid,
    email,
    stripe_price_id,
    product_name: productConfig.name,
    type: orderType,
    amount: price.unit_amount,
    currency: price.currency,
    payment_method,
    status: "pending",
  });

  return { order, productConfig, price };
}

exports.createCheckoutSession = async (req, res) => {
  const { stripe_price_id, user_uuid, email } = req.body;

  if (!stripe_price_id || !user_uuid) {
    return res
      .status(400)
      .json({ error: "Missing required fields: stripe_price_id, user_uuid" });
  }

  try {
    // 检查用户等级是否满足产品要求
    const membershipCheck = await checkUserMembershipLevel(
      stripe_price_id,
      user_uuid
    );
    if (!membershipCheck.success) {
      return res.status(403).json({
        error: "会员等级不足",
        message: membershipCheck.message,
        required_tier: membershipCheck.required_tier,
        current_tier: membershipCheck.current_tier,
        membership_expired: membershipCheck.membership_expired,
      });
    }

    const { order, productConfig } = await createOrder(
      stripe_price_id,
      user_uuid,
      email,
      "checkout"
    );
    s;
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ["card"],
      line_items: [{ price: stripe_price_id, quantity: 1 }],
      mode:
        productConfig.product_type === "subscription"
          ? "subscription"
          : "payment",
      success_url: "https://www.know1.ai/",
      cancel_url: "https://www.know1.ai/",
      metadata: {
        order_id: order.id,
        user_uuid,
        stripe_price_id,
      },
    });

    await order.update({ stripe_session_id: session.id });

    console.log("订单创建成功:", order.id);
    res.json({ url: session.url, order_id: order.id });
  } catch (err) {
    console.error("创建订单失败:", err.message);
    res.status(500).json({ error: err.message });
  }
};

// ========== Stripe Elements 相关方法 ==========
// Stripe Elements - 创建 PaymentIntent（一次性支付）
exports.createPaymentIntent = async (req, res) => {
  const { stripe_price_id, user_uuid, email } = req.body;

  if (!stripe_price_id || !user_uuid) {
    return res
      .status(400)
      .json({ error: "Missing required fields: stripe_price_id, user_uuid" });
  }

  try {
    // 检查用户等级是否满足产品要求
    const membershipCheck = await checkUserMembershipLevel(
      stripe_price_id,
      user_uuid
    );
    if (!membershipCheck.success) {
      return res.status(403).json({
        error: "会员等级不足",
        message: membershipCheck.message,
        required_tier: membershipCheck.required_tier,
        current_tier: membershipCheck.current_tier,
        membership_expired: membershipCheck.membership_expired,
      });
    }

    const { order, price } = await createOrder(
      stripe_price_id,
      user_uuid,
      email,
      "elements"
    );

    const paymentIntent = await stripe.paymentIntents.create({
      amount: price.unit_amount,
      currency: price.currency,
      payment_method_types: ["card"],
      metadata: {
        order_id: order.id,
        user_uuid,
        stripe_price_id,
      },
      payment_method_options: {
        card: {
          request_three_d_secure: "automatic",
        },
      },
    });

    await order.update({ stripe_payment_intent_id: paymentIntent.id });

    console.log("PaymentIntent创建成功:", paymentIntent.id);
    res.json({
      clientSecret: paymentIntent.client_secret,
      amount: price.unit_amount,
      currency: price.currency,
      order_id: order.id,
    });
  } catch (err) {
    console.error("创建 PaymentIntent 失败:", err.message);
    res.status(500).json({ error: err.message });
  }
};

// Stripe Elements - 创建 Subscription（订阅）
exports.createSubscription = async (req, res) => {
  const { email, stripe_price_id, user_uuid } = req.body;

  if (!stripe_price_id || !user_uuid || !email) {
    return res.status(400).json({
      error: "Missing required fields: stripe_price_id, user_uuid, email",
    });
  }

  try {
    // 订阅接口不需要判断会员等级

    // 验证产品配置
    const productConfig = await ProductConfig.findOne({
      where: { stripe_price_id, is_active: true, product_type: "subscription" },
    });

    if (!productConfig) {
      return res
        .status(400)
        .json({ error: "Invalid or inactive subscription product" });
    }

    // 创建或查找 customer
    let customer;
    const existingCustomers = await stripe.customers.list({
      email: email,
      limit: 1,
    });

    if (existingCustomers.data.length > 0) {
      customer = existingCustomers.data[0];
    } else {
      customer = await stripe.customers.create({
        email: email,
        metadata: {
          user_uuid: user_uuid,
          source: "stripe_elements",
        },
      });
    }

    // 使用通用的createOrder函数创建订单，确保获取正确的价格信息
    const { order, price } = await createOrder(
      stripe_price_id,
      user_uuid,
      email,
      "elements"
    );

    console.log(`订单创建成功: ${order.id}, 开始创建订阅...`);

    // 创建 subscription
    const subscription = await stripe.subscriptions.create({
      customer: customer.id,
      items: [{ price: stripe_price_id }],
      payment_behavior: "default_incomplete",
      payment_settings: {
        save_default_payment_method: "on_subscription",
      },
      metadata: {
        order_id: order.id,
        user_uuid,
        membership_tier: productConfig.membership_tier,
      },
      expand: ["latest_invoice.payment_intent"],
    });

    // 更新订单，包括金额信息
    await order.update({
      stripe_subscription_id: subscription.id,
      amount: subscription.latest_invoice
        ? subscription.latest_invoice.amount_due
        : 0,
      currency: subscription.latest_invoice
        ? subscription.latest_invoice.currency || "jpy"
        : "jpy",
    });

    // 检查订阅对象结构
    if (!subscription.latest_invoice) {
      console.error(`订阅 ${subscription.id} 没有latest_invoice属性`);
      return res
        .status(500)
        .json({ error: "Subscription created but no invoice available" });
    }

    if (!subscription.latest_invoice.payment_intent) {
      console.error(`订阅 ${subscription.id} 的发票没有payment_intent属性`);
      console.log(
        `发票状态: ${subscription.latest_invoice.status}, 应付金额: ${subscription.latest_invoice.amount_due}`
      );

      // 如果发票已经支付或者金额为0，可能不需要PaymentIntent
      if (
        subscription.latest_invoice.status === "paid" ||
        subscription.latest_invoice.amount_due === 0
      ) {
        console.log("发票已支付或金额为0，直接激活订阅");

        // 直接处理订阅激活 - 确保订单包含正确的 stripe_subscription_id
        await order.update({ status: "succeeded" });
        console.log(`订阅ID已设置: ${order.stripe_subscription_id}`);
        await grantTokens(order);

        return res.json({
          subscriptionId: subscription.id,
          customerId: customer.id,
          order_id: order.id,
          amount: subscription.latest_invoice.amount_due,
          currency: subscription.latest_invoice.currency || "hkd",
          status: "activated",
          message: "Subscription activated successfully",
        });
      }

      // 如果发票未支付且金额大于0，处理支付
      if (
        subscription.latest_invoice.status === "open" &&
        subscription.latest_invoice.amount_due > 0
      ) {
        console.log("发票未支付，检查发票状态并创建PaymentIntent");

        try {
          // 获取发票的完整信息
          const invoice = await stripe.invoices.retrieve(
            subscription.latest_invoice.id,
            { expand: ["payment_intent"] }
          );

          console.log(
            `发票详情: ID=${invoice.id}, 状态=${invoice.status}, 是否已完成=${
              invoice.status === "open" ? "否" : "是"
            }`
          );

          // 如果发票已有PaymentIntent，直接使用
          if (invoice.payment_intent) {
            console.log(`发票已有PaymentIntent: ${invoice.payment_intent.id}`);

            // 更新PaymentIntent的元数据
            await stripe.paymentIntents.update(invoice.payment_intent.id, {
              metadata: {
                subscription_id: subscription.id,
                order_id: order.id,
                user_uuid,
                invoice_id: invoice.id,
              },
            });

            return res.json({
              clientSecret: invoice.payment_intent.client_secret,
              subscriptionId: subscription.id,
              customerId: customer.id,
              order_id: order.id,
              paymentIntentId: invoice.payment_intent.id,
              invoiceId: invoice.id,
              amount: invoice.amount_due,
              currency: invoice.currency || "hkd",
              message: "Subscription created, using existing payment intent",
            });
          }

          // 如果发票是草稿状态，尝试完成它
          if (invoice.status === "draft") {
            console.log("发票是草稿状态，尝试完成发票");
            const finalizedInvoice = await stripe.invoices.finalizeInvoice(
              invoice.id
            );

            if (finalizedInvoice.payment_intent) {
              console.log(
                `完成发票后创建了PaymentIntent: ${finalizedInvoice.payment_intent}`
              );

              const paymentIntent = await stripe.paymentIntents.retrieve(
                finalizedInvoice.payment_intent
              );

              // 更新PaymentIntent的元数据
              await stripe.paymentIntents.update(paymentIntent.id, {
                metadata: {
                  subscription_id: subscription.id,
                  order_id: order.id,
                  user_uuid,
                  invoice_id: finalizedInvoice.id,
                },
              });

              return res.json({
                clientSecret: paymentIntent.client_secret,
                subscriptionId: subscription.id,
                customerId: customer.id,
                order_id: order.id,
                paymentIntentId: paymentIntent.id,
                invoiceId: finalizedInvoice.id,
                amount: finalizedInvoice.amount_due,
                currency: finalizedInvoice.currency || "hkd",
                message: "Subscription created, invoice finalized",
              });
            }
          }

          // 如果发票已完成但没有PaymentIntent，为发票创建PaymentIntent
          console.log("发票已完成但没有PaymentIntent，为发票创建PaymentIntent");
          const paymentIntent = await stripe.paymentIntents.create({
            amount: invoice.amount_due,
            currency: invoice.currency || "hkd",
            customer: customer.id,
            payment_method_types: ["card"],
            metadata: {
              subscription_id: subscription.id,
              order_id: order.id,
              user_uuid,
              invoice_id: invoice.id,
            },
            payment_method_options: {
              card: {
                request_three_d_secure: "automatic",
              },
            },
          });

          console.log(`为已完成发票创建PaymentIntent成功: ${paymentIntent.id}`);

          // 更新订单金额信息
          await order.update({
            amount: invoice.amount_due,
            currency: invoice.currency || "hkd",
          });

          return res.json({
            clientSecret: paymentIntent.client_secret,
            subscriptionId: subscription.id,
            customerId: customer.id,
            order_id: order.id,
            paymentIntentId: paymentIntent.id,
            invoiceId: invoice.id,
            amount: invoice.amount_due,
            currency: invoice.currency || "hkd",
            message:
              "Subscription created, payment intent created for finalized invoice",
          });
        } catch (invoiceProcessError) {
          console.error("处理发票失败:", invoiceProcessError.message);

          // 最后的回退方案：创建独立的PaymentIntent
          console.log("创建独立的PaymentIntent作为最后回退方案");
          const paymentIntent = await stripe.paymentIntents.create({
            amount: subscription.latest_invoice.amount_due,
            currency: subscription.latest_invoice.currency || "hkd",
            customer: customer.id,
            payment_method_types: ["card"],
            metadata: {
              subscription_id: subscription.id,
              order_id: order.id,
              user_uuid,
              invoice_id: subscription.latest_invoice.id,
            },
            payment_method_options: {
              card: {
                request_three_d_secure: "automatic",
              },
            },
          });

          console.log(`回退方案创建PaymentIntent成功: ${paymentIntent.id}`);
          console.log("⚠️ 注意：此PaymentIntent支付成功后需要手动处理订阅激活");

          // 更新订单金额信息
          await order.update({
            amount: subscription.latest_invoice.amount_due,
            currency: subscription.latest_invoice.currency || "hkd",
          });

          return res.json({
            clientSecret: paymentIntent.client_secret,
            subscriptionId: subscription.id,
            customerId: customer.id,
            order_id: order.id,
            paymentIntentId: paymentIntent.id,
            invoiceId: subscription.latest_invoice.id,
            amount: subscription.latest_invoice.amount_due,
            currency: subscription.latest_invoice.currency || "hkd",
            message: "Subscription created, payment required (fallback method)",
          });
        }
      }

      // 尝试手动获取发票和支付意图
      try {
        console.log(`尝试手动获取发票: ${subscription.latest_invoice.id}`);
        const invoice = await stripe.invoices.retrieve(
          subscription.latest_invoice.id,
          {
            expand: ["payment_intent"],
          }
        );

        // console.log("手动获取的发票信息:", JSON.stringify({
        //   id: invoice.id,
        //   status: invoice.status,
        //   amount_due: invoice.amount_due,
        //   payment_intent: invoice.payment_intent ? {
        //     id: invoice.payment_intent.id,
        //     status: invoice.payment_intent.status,
        //     client_secret: invoice.payment_intent.client_secret ? "存在" : "不存在"
        //   } : null
        // }, null, 2));

        if (
          invoice &&
          invoice.payment_intent &&
          invoice.payment_intent.client_secret
        ) {
          console.log(`成功获取发票的支付意图: ${invoice.payment_intent.id}`);

          // 更新PaymentIntent元数据
          try {
            await stripe.paymentIntents.update(invoice.payment_intent.id, {
              metadata: {
                subscription_id: subscription.id,
                order_id: order.id,
                user_uuid,
              },
            });
            console.log("PaymentIntent元数据更新成功");
          } catch (metadataErr) {
            console.error("更新PaymentIntent元数据失败:", metadataErr.message);
          }

          // 返回客户端所需信息
          return res.json({
            clientSecret: invoice.payment_intent.client_secret,
            subscriptionId: subscription.id,
            customerId: customer.id,
            order_id: order.id,
            amount: invoice.amount_due,
            currency: invoice.currency || "hkd",
          });
        }
      } catch (invoiceError) {
        console.error(`获取发票失败: ${invoiceError.message}`);
      }

      return res.status(500).json({
        error: "Subscription created but payment intent not available",
        subscriptionId: subscription.id,
        customerId: customer.id,
        order_id: order.id,
        amount: subscription.latest_invoice.amount_due,
        currency: subscription.latest_invoice.currency || "hkd",
        debug: {
          invoice_status: subscription.latest_invoice.status,
          amount_due: subscription.latest_invoice.amount_due,
          amount_paid: subscription.latest_invoice.amount_paid,
        },
      });
    }

    // 重要：添加订阅ID到payment_intent的metadata中
    if (
      subscription.latest_invoice &&
      subscription.latest_invoice.payment_intent
    ) {
      console.log(`更新PaymentIntent元数据，添加订阅ID: ${subscription.id}`);
      try {
        await stripe.paymentIntents.update(
          subscription.latest_invoice.payment_intent.id,
          {
            metadata: {
              subscription_id: subscription.id,
              order_id: order.id,
              user_uuid,
            },
          }
        );
        console.log("PaymentIntent元数据更新成功");
      } catch (metadataErr) {
        console.error("更新PaymentIntent元数据失败:", metadataErr.message);
        // 即使更新失败也继续处理，因为主要订单信息已经记录
      }
    } else {
      console.warn("未找到订阅关联的PaymentIntent，无法更新元数据");
    }

    console.log(`订阅创建完成，返回客户端所需信息: ${subscription.id}`);
    res.json({
      clientSecret: subscription.latest_invoice.payment_intent.client_secret,
      subscriptionId: subscription.id,
      customerId: customer.id,
      order_id: order.id,
      amount: subscription.latest_invoice.amount_due,
      currency: subscription.latest_invoice.currency || "hkd",
    });
  } catch (err) {
    console.error("创建 Subscription 失败:", err.message, err.stack);
    res.status(500).json({ error: err.message });
  }
};

// ========== 取消订阅 ==========
exports.cancelSubscription = async (req, res) => {
  const user_uuid = req.visitor.uuid;

  if (!user_uuid) {
    return res.status(400).json({ error: "User UUID not found in token" });
  }

  try {
    // 查找用户的权益记录以获取订阅 ID
    const userBenefit = await UserBenefit.findOne({
      where: { user_uuid },
    });

    if (!userBenefit || !userBenefit.stripe_subscription_id) {
      return res
        .status(404)
        .json({ error: "No active subscription found for this user" });
    }

    // 获取订阅信息
    const subscription = await stripe.subscriptions.retrieve(
      userBenefit.stripe_subscription_id
    );

    if (!subscription) {
      return res
        .status(404)
        .json({ error: "Subscription not found in Stripe" });
    }

    // 取消订阅，设置 cancel_at_period_end 为 true，这样用户可以继续使用到当前计费周期结束
    const updatedSubscription = await stripe.subscriptions.update(
      subscription.id,
      { cancel_at_period_end: true }
    );

    // 更新用户权益记录中的订阅状态
    await userBenefit.update({
      subscription_status: "cancelled",
      membership_tier: null,
    });

    // 同时更新Visitor表中的会员等级
    await Visitor.update(
      { membership_tier: null },
      { where: { uuid: user_uuid } }
    );

    // 返回取消的信息
    res.json({
      message:
        "Subscription will be canceled at the end of the current billing period",
      current_period_end: new Date(subscription.current_period_end * 1000),
    });
  } catch (err) {
    console.error("取消订阅失败:", err.message);
    res.status(500).json({ error: err.message });
  }
};

// ========== 立即取消订阅 ==========
exports.cancelSubscriptionImmediately = async (req, res) => {
  const user_uuid = req.visitor.uuid;

  if (!user_uuid) {
    return res.status(400).json({ error: "User UUID not found in token" });
  }

  try {
    // 查找用户的权益记录以获取订阅 ID
    const userBenefit = await UserBenefit.findOne({
      where: { user_uuid },
    });

    if (!userBenefit || !userBenefit.stripe_subscription_id) {
      return res
        .status(404)
        .json({ error: "No active subscription found for this user" });
    }

    // 获取订阅信息
    const subscription = await stripe.subscriptions.retrieve(
      userBenefit.stripe_subscription_id
    );

    if (!subscription) {
      return res
        .status(404)
        .json({ error: "Subscription not found in Stripe" });
    }

    // 立即取消订阅
    const canceledSubscription = await stripe.subscriptions.del(
      subscription.id
    );

    // 更新用户权益记录中的订阅状态
    await userBenefit.update({
      subscription_status: "cancelled",
      stripe_subscription_id: null,
      membership_tier: null,
    });

    // 同时更新Visitor表中的会员等级
    await Visitor.update(
      { membership_tier: null },
      { where: { uuid: user_uuid } }
    );

    // 返回取消的信息
    res.json({
      message: "Subscription has been canceled immediately",
      canceled_at: new Date(),
    });
  } catch (err) {
    console.error("立即取消订阅失败:", err.message);
    res.status(500).json({ error: err.message });
  }
};

// 处理支付完成（首次支付）
async function handlePaymentCompleted(stripeObject, source) {
  try {
    console.log(
      `处理${source}支付，对象:`,
      JSON.stringify(
        {
          id: stripeObject.id,
          object: stripeObject.object,
          metadata: stripeObject.metadata,
          subscription: stripeObject.subscription,
          customerId: stripeObject.customer,
        },
        null,
        2
      )
    );

    const orderId = stripeObject.metadata.order_id;
    if (!orderId) {
      console.error("支付对象缺少order_id，无法处理:", stripeObject.id);
      return;
    }

    const order = await PaymentOrder.findByPk(orderId);
    if (!order) {
      console.error(`找不到订单ID: ${orderId}`);
      return;
    }

    // 获取产品配置，添加产品名称
    const productConfig = await ProductConfig.findOne({
      where: { stripe_price_id: order.stripe_price_id },
    });

    // 更新订单状态 - 立即将订单标记为成功
    const updateData = {
      status: "succeeded",
      product_name: productConfig ? productConfig.name : null,
    };

    // 检查订阅ID（适用于checkout和elements支付）
    if (stripeObject.subscription) {
      updateData.stripe_subscription_id = stripeObject.subscription;
      console.log(
        `从stripeObject.subscription获取订阅ID: ${stripeObject.subscription}`
      );
    } else if (stripeObject.metadata && stripeObject.metadata.subscription_id) {
      updateData.stripe_subscription_id = stripeObject.metadata.subscription_id;
      console.log(
        `从metadata.subscription_id获取订阅ID: ${stripeObject.metadata.subscription_id}`
      );
    }

    // 如果订单金额为0，尝试从支付意图获取金额
    if (order.amount === 0 && stripeObject.amount) {
      updateData.amount = stripeObject.amount;
      updateData.currency = stripeObject.currency || order.currency;
      console.log(
        `从支付意图获取金额: ${stripeObject.amount} ${
          stripeObject.currency || order.currency
        }`
      );
    }

    console.log(`更新订单 ${orderId}:`, updateData);
    await order.update(updateData);

    // 立即发放代币和权益 - 这是修改的关键部分
    console.log(`立即为订单 ${orderId} 发放代币和权益`);
    await grantTokens(order);
    
    // 对于Elements支付，确保客户有默认支付方式用于自动续费（这部分移到代币发放之后）
    if (
      source === "elements" &&
      stripeObject.customer &&
      stripeObject.payment_method
    ) {
      try {
        console.log(
          `处理客户 ${stripeObject.customer} 的支付方式: ${stripeObject.payment_method}`
        );

        // 获取客户信息
        const customer = await stripe.customers.retrieve(stripeObject.customer);

        // 检查客户是否已有默认支付方式
        if (!customer.invoice_settings?.default_payment_method) {
          console.log(`客户没有默认支付方式，开始处理...`);

          // 先检查客户现有的支付方式
          const existingPaymentMethods = await stripe.paymentMethods.list({
            customer: stripeObject.customer,
            type: "card",
          });

          let targetPaymentMethod = null;

          // 检查当前支付方式是否已经附加到客户
          const currentPmAttached = existingPaymentMethods.data.find(
            (pm) => pm.id === stripeObject.payment_method
          );

          if (currentPmAttached) {
            console.log(
              `支付方式 ${stripeObject.payment_method} 已经附加到客户`
            );
            targetPaymentMethod = stripeObject.payment_method;
          } else if (existingPaymentMethods.data.length > 0) {
            // 如果有其他可用的支付方式，使用第一个
            targetPaymentMethod = existingPaymentMethods.data[0].id;
            console.log(`使用客户已有的支付方式: ${targetPaymentMethod}`);
          } else {
            // 尝试附加当前支付方式
            try {
              console.log(
                `尝试将支付方式 ${stripeObject.payment_method} 附加到客户`
              );
              await stripe.paymentMethods.attach(stripeObject.payment_method, {
                customer: stripeObject.customer,
              });
              console.log(`支付方式附加成功`);
              targetPaymentMethod = stripeObject.payment_method;
            } catch (attachError) {
              console.log(`附加支付方式失败: ${attachError.message}`);

              // 如果是测试模式下PaymentMethod已被使用的错误，记录日志但继续主流程
              if (
                attachError.message.includes("previously used") ||
                attachError.message.includes("may not be used again")
              ) {
                console.log(
                  `⚠️  测试模式下PaymentMethod重复使用错误，跳过设置默认支付方式`
                );
                console.log(
                  `💡 提示: 支付已成功完成，自动续费将依赖Stripe的save_default_payment_method配置`
                );
                // 不要return，继续执行主流程
              } else {
                throw attachError;
              }
            }
          }

          // 如果找到了可用的支付方式，设置为默认
          if (targetPaymentMethod) {
            console.log(
              `设置支付方式 ${targetPaymentMethod} 为客户默认支付方式`
            );
            await stripe.customers.update(stripeObject.customer, {
              invoice_settings: {
                default_payment_method: targetPaymentMethod,
              },
            });
            console.log(
              `✅ 已成功设置客户 ${stripeObject.customer} 的默认支付方式为: ${targetPaymentMethod}`
            );
          }
        } else {
          console.log(
            `客户 ${stripeObject.customer} 已有默认支付方式: ${customer.invoice_settings.default_payment_method}`
          );
        }
      } catch (paymentMethodError) {
        console.error("❌ 处理客户支付方式失败:", paymentMethodError.message);
        console.log(`💡 支付已成功，将依赖Stripe的自动保存配置进行续费`);
        // 不影响主流程，继续处理
      }
    }

    // 如果是订阅支付成功，还需要激活订阅
    if (stripeObject.metadata && stripeObject.metadata.subscription_id) {
      try {
        console.log(`尝试激活订阅: ${stripeObject.metadata.subscription_id}`);

        // 获取当前订阅状态
        const subscription = await stripe.subscriptions.retrieve(
          stripeObject.metadata.subscription_id
        );
        console.log(`当前订阅状态: ${subscription.status}`);

        // 对于我们的业务逻辑，PaymentIntent 支付成功就意味着订阅有效
        // 不需要等待 Stripe 将订阅状态改为 active
        if (subscription.status === "incomplete") {
          console.log("订阅状态为 incomplete，但支付已成功，视为订阅有效");
        }

        console.log(`订阅处理完成，当前状态: ${subscription.status}`);
      } catch (subscriptionError) {
        console.error("处理订阅激活失败:", subscriptionError.message);
      }
    }

    console.log(`${source} 支付完成，订单ID: ${orderId}`);
  } catch (err) {
    console.error("处理支付完成事件失败:", err.message, err.stack);
  }
}

// 处理订阅续费（invoice.payment_succeeded）
async function handleSubscriptionRenewal(invoice) {
  const transaction = await sequelize.transaction();

  try {
    const subscriptionId = invoice.subscription;
    const priceId = invoice.lines.data[0].price.id;

    // 找到对应的用户
    const userBenefit = await UserBenefit.findOne({
      where: { stripe_subscription_id: subscriptionId },
      transaction,
    });

    if (!userBenefit) {
      await transaction.rollback();
      return;
    }

    const visitor = await Visitor.findOne({
      where: { uuid: userBenefit.user_uuid },
      transaction,
      lock: transaction.LOCK.UPDATE,
    });

    const productConfig = await ProductConfig.findOne({
      where: { stripe_price_id: priceId },
      transaction,
    });

    if (visitor && productConfig) {
      // 获取最新的订阅信息
      const subscription = await stripe.subscriptions.retrieve(subscriptionId);
      const newExpiresAt = new Date(subscription.current_period_end * 1000);
      const tokenAmount = productConfig.tokens_amount;

      // 创建续费支付订单记录
      await PaymentOrder.create(
        {
          user_uuid: visitor.uuid,
          email: visitor.email,
          stripe_price_id: priceId,
          product_name: productConfig.name,
          type: "subscription", // 订阅续费应该是 subscription 类型
          stripe_subscription_id: subscriptionId,
          amount: invoice.amount_due,
          currency: invoice.currency || "hkd",
          status: "succeeded",
          payment_method: "subscription_renewal",
        },
        { transaction }
      );

      // 从tokenController导入代币管理函数
      const { addTokensBySource } = require("./tokenController");

      // 使用新的代币来源管理：增加购买代币
      const newBalances = await addTokensBySource(
        visitor,
        tokenAmount,
        "purchased",
        transaction
      );

      // 更新会员到期时间和会员等级
      await visitor.update(
        {
          membership_expires_at: newExpiresAt,
          membership_tier: productConfig.membership_tier,
        },
        { transaction }
      );

      // 更新统计
      await userBenefit.update(
        {
          total_tokens_granted: userBenefit.total_tokens_granted + tokenAmount,
          // 确保会员等级与当前产品配置一致
          membership_tier:
            productConfig.membership_tier || userBenefit.membership_tier,
        },
        { transaction }
      );

      // 记录代币交易
      await TokenTransaction.create(
        {
          user_uuid: userBenefit.user_uuid,
          type: "subscription_grant",
          amount: tokenAmount,
          balance_after: newBalances.tokens_balance,
          description: `订阅续费赠送 ${tokenAmount} 代币`,
          token_source: "purchased",
          status: "confirmed",
          payment_order_id: subscriptionId, // 使用订阅ID
          server_type: "text", // 使用text作为安全的备用选项
        },
        { transaction }
      );

      console.log(
        `用户 ${userBenefit.user_uuid} 订阅续费，累加 ${tokenAmount} 购买代币，总余额: ${newBalances.tokens_balance}，购买代币余额: ${newBalances.tokens_purchased}`
      );
    }

    await transaction.commit();
  } catch (err) {
    await transaction.rollback();
    console.error("处理订阅续费失败:", err.message);
  }
}

// 处理订阅取消
async function handleSubscriptionCancelled(subscription) {
  try {
    await UserBenefit.update(
      {
        subscription_status: "cancelled",
        stripe_subscription_id: null,
        // 不清除会员等级，让其自然到期
      },
      { where: { stripe_subscription_id: subscription.id } }
    );

    // 注意：不清空用户的会员到期时间，让其自然到期
    // 也不清空代币余额，让用户继续使用剩余代币

    console.log(
      `订阅已取消: ${subscription.id}，用户代币和会员时间保持到自然到期`
    );
  } catch (err) {
    console.error("处理订阅取消失败:", err.message);
  }
}

// 发放代币 - 使用新的代币来源管理系统
async function grantTokens(order) {
  console.log(
    `开始为订单 ${order.id} 发放代币，产品ID: ${
      order.stripe_price_id
    }，订阅ID: ${order.stripe_subscription_id || "无"}`
  );
  console.log(
    `订单详情: payment_method=${order.payment_method}, type=${order.type}, status=${order.status}`
  );

  const transaction = await sequelize.transaction();

  try {
    const productConfig = await ProductConfig.findOne({
      where: { stripe_price_id: order.stripe_price_id },
    });

    if (!productConfig) {
      console.error(`找不到产品配置，价格ID: ${order.stripe_price_id}`);
      await transaction.rollback();
      return;
    }

    console.log(
      `找到产品配置: ${productConfig.name}, 类型: ${productConfig.product_type}, 代币: ${productConfig.tokens_amount}`
    );

    // 获取用户信息（加锁）
    const visitor = await Visitor.findOne({
      where: { uuid: order.user_uuid },
      transaction,
      lock: transaction.LOCK.UPDATE,
    });

    if (!visitor) {
      console.error(`找不到用户，UUID: ${order.user_uuid}`);
      await transaction.rollback();
      return;
    }

    console.log(`找到用户: ${visitor.uuid}, 邮箱: ${visitor.email}`);

    // 获取或创建用户权益记录
    let userBenefit = await UserBenefit.findOne({
      where: { user_uuid: order.user_uuid },
      transaction,
    });

    if (!userBenefit) {
      userBenefit = await UserBenefit.create(
        {
          user_uuid: order.user_uuid,
        },
        { transaction }
      );
    }

    const tokenAmount = productConfig.tokens_amount;

    // 从tokenController导入代币管理函数
    const { addTokensBySource } = require("./tokenController");

    // 检查产品类型和订阅状态
    console.log(
      `产品类型: ${
        productConfig.product_type
      }, 订阅ID存在: ${!!order.stripe_subscription_id}`
    );

    if (
      productConfig.product_type === "subscription" &&
      order.stripe_subscription_id
    ) {
      try {
        console.log(`尝试获取订阅信息: ${order.stripe_subscription_id}`);
        // 订阅：更新会员到期时间 + 发放购买代币
        const subscription = await stripe.subscriptions.retrieve(
          order.stripe_subscription_id
        );

        if (!subscription) {
          throw new Error(
            `无法获取订阅信息，订阅ID: ${order.stripe_subscription_id}`
          );
        }

        console.log(
          `订阅信息: 状态=${subscription.status}, 当前期间结束=${subscription.current_period_end}`
        );

        // 处理订阅到期时间
        let expiresAt;
        if (subscription.current_period_end) {
          expiresAt = new Date(subscription.current_period_end * 1000);
        } else {
          // 如果订阅状态为 incomplete 或没有 current_period_end，设置为当前时间加30天
          console.log("订阅状态为 incomplete 或缺少到期时间，设置默认到期时间");
          expiresAt = new Date();
          expiresAt.setDate(expiresAt.getDate() + 30); // 30天后到期
        }

        // 使用新的代币来源管理：增加购买代币
        console.log(`为用户 ${visitor.uuid} 添加 ${tokenAmount} 代币`);
        const newBalances = await addTokensBySource(
          visitor,
          tokenAmount,
          "purchased",
          transaction
        );

        // 更新会员到期时间和会员等级
        console.log(`更新会员到期时间: ${expiresAt.toISOString()}`);
        console.log(`更新会员等级: ${productConfig.membership_tier || "无"}`);
        await visitor.update(
          {
            membership_expires_at: expiresAt,
            membership_tier: productConfig.membership_tier,
          },
          { transaction }
        );

        // 更新权益统计 - 修复订阅状态值
        console.log(
          `更新用户权益记录: 订阅状态=${subscription.status}, 会员等级=${
            productConfig.membership_tier || "无"
          }`
        );
        
        // 确保订阅状态符合数据库枚举类型
        let validSubscriptionStatus = 'active';
        if (subscription.status === 'incomplete') {
          validSubscriptionStatus = 'active'; // 因为已经付款成功了，所以视为active
        } else if (subscription.status === 'canceled') {
          validSubscriptionStatus = 'cancelled'; // 统一拼写方式
        } else if (subscription.status === 'past_due' || subscription.status === 'unpaid') {
          validSubscriptionStatus = 'active'; // 视为active，以便让用户使用
        } else if (subscription.status === 'trialing') {
          validSubscriptionStatus = 'active';
        } else {
          validSubscriptionStatus = subscription.status;
        }
        
        await userBenefit.update(
          {
            stripe_subscription_id: order.stripe_subscription_id,
            subscription_status: validSubscriptionStatus,
            total_tokens_granted:
              userBenefit.total_tokens_granted + tokenAmount,
            // 设置会员等级
            membership_tier: productConfig.membership_tier,
          },
          { transaction }
        );

        // 记录代币交易
        console.log(
          `记录代币交易: 类型=subscription_grant, 数量=${tokenAmount}`
        );

        // 根据支付方式确定描述和支付订单ID
        let description, paymentOrderId;
        if (order.payment_method === "elements") {
          description = "subscription";
          paymentOrderId = order.stripe_subscription_id || order.id; // 如果没有订阅ID则使用订单ID
        } else {
          description = `订阅赠送 ${tokenAmount} 代币`;
          paymentOrderId = order.id;
        }

        // 确保server_type的值是有效的枚举值
        const serverType = 'subscription'; // 这是数据库中定义的有效枚举值
        
        await TokenTransaction.create(
          {
            user_uuid: order.user_uuid,
            type: "subscription_grant",
            amount: tokenAmount,
            balance_after: newBalances.tokens_balance,
            payment_order_id: paymentOrderId,
            description: description,
            token_source: "purchased",
            status: "confirmed",
            server_type: "text", // 使用text作为安全的备用选项
          },
          { transaction }
        );

        console.log(
          `用户 ${
            order.user_uuid
          } 开通订阅至 ${expiresAt}，获得 ${tokenAmount} 购买代币，会员等级：${
            productConfig.membership_tier || "无"
          }`
        );
      } catch (subscriptionError) {
        console.error(
          "获取订阅信息失败，作为普通代币购买处理:",
          subscriptionError.message,
          subscriptionError.stack
        );

        // 尝试一次直接通过API获取订阅信息（可能是内部引用的问题）
        try {
          console.log("尝试直接通过API获取订阅信息...");
          const Stripe = require("stripe");
          const stripeDirectApi = Stripe(
            process.env.STRIPE_SECRET_KEY ||
              "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"
          );

          const subscription = await stripeDirectApi.subscriptions.retrieve(
            order.stripe_subscription_id
          );
          console.log("成功获取订阅信息:", subscription.id);

          // 如果直接API调用成功，更新订单状态，但仍按普通购买处理
          await order.update({
            subscription_status: 'active', // 使用有效的订阅状态
          });
        } catch (directApiError) {
          console.error("直接API调用也失败:", directApiError.message);
        }

        // 订阅信息获取失败，按普通代币购买处理
        console.log("继续按普通代币购买处理...");
        await handleTokenPurchase(
          order,
          visitor,
          userBenefit,
          tokenAmount,
          transaction
        );
      }
    } else {
      // 一次性购买或订阅ID不存在：发放购买代币
      if (
        productConfig.product_type === "subscription" &&
        !order.stripe_subscription_id
      ) {
        console.log("警告：产品为订阅类型，但订单没有订阅ID，按普通购买处理");
      } else {
        console.log("普通代币购买");
      }
      await handleTokenPurchase(
        order,
        visitor,
        userBenefit,
        tokenAmount,
        transaction
      );
    }

    await transaction.commit();
  } catch (err) {
    await transaction.rollback();
    console.error("发放代币失败:", err.message);
  }
}

// 处理代币购买（抽取为独立函数以复用代码）
async function handleTokenPurchase(
  order,
  visitor,
  userBenefit,
  tokenAmount,
  transaction
) {
  // 从tokenController导入代币管理函数
  const { addTokensBySource } = require("./tokenController");

  const newBalances = await addTokensBySource(
    visitor,
    tokenAmount,
    "purchased",
    transaction
  );

  // 更新权益统计
  await userBenefit.update(
    {
      total_tokens_purchased: userBenefit.total_tokens_purchased + tokenAmount,
    },
    { transaction }
  );

  // 根据支付方式确定描述和支付订单ID
  let description, paymentOrderId;
  if (order.payment_method === "elements") {
    description = "disposable";
    paymentOrderId = order.stripe_payment_intent_id || order.id; // 如果没有支付意图ID则使用订单ID
  } else {
    description = `购买 ${tokenAmount} 代币`;
    paymentOrderId = order.id;
  }

  // 确保server_type的值是有效的枚举值（使用固定字符串而不是变量）
  await TokenTransaction.create(
    {
      user_uuid: order.user_uuid,
      type: "purchase",
      amount: tokenAmount,
      balance_after: newBalances.tokens_balance,
      payment_order_id: paymentOrderId,
      description: description,
      token_source: "purchased",
      status: "confirmed",
      server_type: "text", // 使用text作为安全的备用选项
    },
    { transaction }
  );

  console.log(
    `用户 ${order.user_uuid} 购买 ${tokenAmount} 代币，购买代币余额: ${newBalances.tokens_purchased}`
  );
}

// Stripe Webhook 处理
exports.handleWebhook = (req, res) => {
  const sig = req.headers["stripe-signature"];
  
  // 使用正确的Webhook签名密钥
  const endpointSecret =
    process.env.STRIPE_WEBHOOK_SECRET || "whsec_JHHsJxtKnWQTxslk91ZVbNRCXe2tZtRw"; 
  
  let event;

  console.log("收到 Stripe Webhook 请求");
  
  try {
    // 确保req.body是Buffer类型，因为bodyParser.raw配置了正确的类型解析
    if (!Buffer.isBuffer(req.body)) {
      console.warn("警告：请求体不是Buffer类型，请确认app.js中正确配置了bodyParser.raw");
    }
    
    // 使用Stripe提供的方法验证签名和构建事件对象
    const Stripe = require("stripe");
    const stripe = Stripe(
      process.env.STRIPE_SECRET_KEY ||
        "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"
    );
    
    event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
    console.log("Webhook 验证通过，事件类型:", event.type);
  } catch (err) {
    console.error("Webhook 验证失败:", err.message);
    // 返回400错误和详细的错误信息
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  // 立即返回200响应，避免Stripe重试，剩余的处理异步进行
  res.json({ received: true });

  // 异步处理事件，不阻塞响应
  (async () => {
    try {
      // 事件类型处理 - 优先处理支付和订阅事件
      switch (event.type) {
        // 支付相关事件最优先
        case "payment_intent.succeeded":
          await handlePaymentCompleted(event.data.object, "elements");
          break;
          
        case "checkout.session.completed":
          await handlePaymentCompleted(event.data.object, "checkout");
          break;
          
        case "invoice.payment_succeeded":
          // 处理订阅续费
          await handleSubscriptionRenewal(event.data.object);
          
          // 检查是否是首次订阅支付
          if (event.data.object.billing_reason === "subscription_create") {
            console.log("检测到首次订阅支付成功，处理订阅激活");
            await handleSubscriptionFirstPayment(event.data.object);
          }
          break;
          
        // 其他事件次优先
        case "customer.subscription.deleted":
          await handleSubscriptionCancelled(event.data.object);
          break;
          
        case "customer.subscription.created":
          await handleSubscriptionCreated(event.data.object);
          break;
          
        // 仅记录信息的事件最后处理  
        case "invoice.created":
          console.log(
            "收到发票创建事件:",
            JSON.stringify({
              id: event.data.object.id,
              subscription: event.data.object.subscription,
              customer: event.data.object.customer,
            })
          );
          break;
          
        case "payment_intent.created":
          console.log(
            "收到支付意图创建事件:",
            JSON.stringify({
              id: event.data.object.id,
              metadata: event.data.object.metadata,
            })
          );
          break;
          
        default:
          console.log(`收到未处理的事件类型: ${event.type}`);
      }
    } catch (err) {
      console.error(`处理 Stripe Webhook 事件 ${event.type} 失败:`, err.message);
    }
  })();
};

// 处理订阅首次支付成功
async function handleSubscriptionFirstPayment(invoice) {
  try {
    console.log(
      `处理订阅首次支付: 发票ID=${invoice.id}, 订阅ID=${invoice.subscription}`
    );

    if (!invoice.subscription) {
      console.error("发票没有关联的订阅ID");
      return;
    }

    // 查找与此订阅关联的订单
    const order = await PaymentOrder.findOne({
      where: { stripe_subscription_id: invoice.subscription },
    });

    if (!order) {
      console.error(`找不到订阅 ${invoice.subscription} 关联的订单`);
      return;
    }

    console.log(`找到关联订单: ${order.id}`);

    // 更新订单状态为成功
    if (order.status !== "succeeded") {
      // 获取产品配置信息
      const productConfig = await ProductConfig.findOne({
        where: { stripe_price_id: order.stripe_price_id },
      });

      // 获取发票详情，确保有正确的金额信息
      try {
        const invoiceDetails = await stripe.invoices.retrieve(invoice.id);
        await order.update({
          status: "succeeded",
          amount: invoiceDetails.amount_due || order.amount,
          currency: invoiceDetails.currency || order.currency,
          product_name: productConfig ? productConfig.name : null,
        });
        console.log(
          `订单 ${order.id} 状态更新为成功，金额: ${
            invoiceDetails.amount_due || order.amount
          } ${invoiceDetails.currency || order.currency}`
        );
      } catch (err) {
        // 如果获取发票详情失败，仍然更新状态
        await order.update({
          status: "succeeded",
          product_name: productConfig ? productConfig.name : null,
        });
        console.log(`订单 ${order.id} 状态更新为成功，但获取发票详情失败`);
      }

      // 立即发放代币和权益
      console.log(`立即为订单 ${order.id} 发放代币`);
      await grantTokens(order);
      console.log(`订单 ${order.id} 代币发放完成`);
    } else {
      console.log(`订单 ${order.id} 已经是成功状态，跳过处理`);
    }
  } catch (err) {
    console.error("处理订阅首次支付失败:", err.message, err.stack);
  }
}

// 处理订阅创建事件
async function handleSubscriptionCreated(subscription) {
  try {
    console.log(`处理订阅创建事件: ${subscription.id}`);

    // 检查metadata中是否有order_id
    if (!subscription.metadata || !subscription.metadata.order_id) {
      console.log(`订阅 ${subscription.id} 没有关联的订单ID，无法处理`);
      return;
    }

    const orderId = subscription.metadata.order_id;
    console.log(`订阅关联的订单ID: ${orderId}`);

    // 更新订单信息
    const order = await PaymentOrder.findByPk(orderId);
    if (!order) {
      console.error(`找不到订单ID: ${orderId}`);
      return;
    }

    // 更新订单的订阅ID
    await order.update({
      stripe_subscription_id: subscription.id,
    });

    console.log(`订单 ${orderId} 已更新订阅ID: ${subscription.id}`);

    // 查找用户权益记录并更新
    const userBenefit = await UserBenefit.findOne({
      where: { user_uuid: order.user_uuid },
    });

    if (userBenefit) {
      // 查找产品配置
      const productConfig = await ProductConfig.findOne({
        where: { stripe_price_id: order.stripe_price_id },
      });

      // 同时更新用户权益和用户表中的会员等级
      await userBenefit.update({
        stripe_subscription_id: subscription.id,
        subscription_status: subscription.status,
        membership_tier: productConfig ? productConfig.membership_tier : null,
      });

      // 同步更新Visitor表中的会员等级
      if (productConfig && productConfig.membership_tier) {
        const visitor = await Visitor.findOne({
          where: { uuid: order.user_uuid },
        });

        if (visitor) {
          await visitor.update({
            membership_tier: productConfig.membership_tier,
          });
          console.log(
            `用户 ${order.user_uuid} 会员等级已同步更新到 ${productConfig.membership_tier}`
          );
        }
      }

      console.log(
        `用户权益记录已更新: 用户=${order.user_uuid}, 订阅ID=${subscription.id}`
      );
    } else {
      console.log(`用户 ${order.user_uuid} 没有权益记录，跳过更新`);
    }
  } catch (err) {
    console.error("处理订阅创建事件失败:", err.message, err.stack);
  }
}
